package main

import (
	"fmt"
	"log"
	"net/http"
	"text/template"
)

func main() {
	go Run()
	fmt.Println("Listen on :7777")
	log.Fatal(http.ListenAndServe(":7777", MainServer))
}

type Server struct{}

var MainServer = &Server{}

func (this *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	router := r.URL.Path
	switch router {
	case "/":
		IndexHandler(w, r)
	default:
		http.NotFound(w, r)
	}
}

var (
	errTpl *template.Template = nil
	errMsg                    = make(map[string]interface{})
)

func init() {
	log.SetFlags(log.Llongfile)

	var err error = nil
	errTpl, err = template.ParseFiles("error.html")
	if nil != err {
		log.Fatal(err)
	}
}

func ErrorHandler(w http.ResponseWriter, msg interface{}) {
	errMsg["error"] = msg
	w.WriteHeader(http.StatusInternalServerError)
	err := errTpl.Execute(w, errMsg)
	if nil != err {
		log.Println(err)
	}
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	tpl, err := template.ParseFiles("index.html")
	if nil != err {
		log.Println(err)
		ErrorHandler(w, err.Error())
		return
	}
	err = tpl.Execute(w, nil)
	if nil != err {
		log.Println(err)
		ErrorHandler(w, err.Error())
	}
}
